﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using log4net;
using System.Web.Security;
using TanHungViet.Helper;

namespace TanHungViet.Web.Models
{
    public class UserRepository
    {
        private static ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private DBTanHungVietEntities _db;

        public UserRepository(DBTanHungVietEntities entity)
        {
            _db = entity;
        }

        public bool CheckUserLogin(string userName, string passWord)
        {
            try
            {
                passWord = FormsAuthentication.HashPasswordForStoringInConfigFile(passWord, "MD5");
                User userLogin = _db.User.FirstOrDefault(b => b.Username == userName && b.Password == passWord);
                if (userLogin != null)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw new ArgumentException(ex.Message);
            }
        }

        public User GetUserByUsername(string userName)
        {
            try
            {
                User result = _db.User.FirstOrDefault(b => b.Username == userName);
                return result != null ? result : null;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw new ArgumentException(ex.Message);
            }
        }

        public void ChangePassword(string userName, string newPassWord)
        {
            try
            {
                User user = GetUserByUsername(userName);
                newPassWord = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassWord, "MD5");
                user.Password = newPassWord;

                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw new ArgumentException(ex.Message);
            }
        }
    }
}
